﻿using System.Linq;
using System.Net.Http.Headers;
using Competition.Infrastructure;
using Competition.Infrastructure.Config;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MiDu.Common;

namespace Competition.App.Web.Controllers
{
    [DisableRequestSizeLimit]
    public class UploadController : Controller
    {
        public IActionResult Index([FromForm]IFormFile file)
        {
            string url = "111";//ImageHelper.UploadImage(file);
            var v = new
            {
                Code = 0,
                Msg = "",
                Data = new
                {
                    src = url
                }
            };
            return Json(v);
        }

        public IActionResult UploadImage()
        {
            IFormFile file = HttpContext.Request.Form.Files.FirstOrDefault();
            string url = AppConfig.OtherConfig.AdminUrl + Upload(file);
            var v = new
            {
                errno = 0,
                data = new string[]
                {
                    url
                }
            };
            return Json(v);
        }

        /// <summary>
        /// 上传图片文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private string Upload(IFormFile file)
        {
            string imgName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
            var ext = System.IO.Path.GetExtension(imgName);  //图片后缀
            imgName = SysHelper.RandomFileName() + ext;
            string imgPath = System.IO.Path.Combine(System.Environment.CurrentDirectory, "wwwroot", "images", imgName);
            FileHelper.StreamToFile(file.OpenReadStream(), imgPath);


            return "/images/" + imgName;
        }
    }
}